package edu.colorado.karl.devices;

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.colorado.karl.databases.ErrorDatabaseResult;
import edu.colorado.karl.databases.LongTermDatabase;
import edu.colorado.karl.databases.SensorResponse;

/**
 * Represents the Hot Water device.  This device is responsible for obtaining
 * and the following information:
 * <ul><li>Domestic Hot Water Temperature</li>
 * <li>Heat Pump Input Pipe Temperature</li>
 * <li>Heat Pump Output Pipe Temperature</li>
 * </ul>
 * @author Michael Knudson
 * @version 4/27/08
 */
public class HotWater {
	//	Used for log4j logging
	private static final Log log = LogFactory.getLog(HotWater.class);

	/**
	 * Sole constructor.
	 */
	public HotWater() {
		
	}

	/**
	 * Returns the domestic hot water temperatures last recorded in the 
	 * Long-Term Database.  If an error occurs while retrieving a temperature, 
	 * the Long_Term_Fail error is set and the value "0.0" is used for that 
	 * temperature.
	 * <p>The values in the double array returned are as follows:
	 * <ul><li>[0] Domestic Hot Water Temperature</li>
	 * <li>[1] Heat Pump DHW In</li>
	 * <li>[2] Heat Pump DHW Out</li>
	 * </ul>
	 * @return a three-element double array containing the domestic hot water
	 * temperatures.
	 */
	public double[] getWaterTemperatures() {
		LongTermDatabase ltdb = new LongTermDatabase();
		double[] temps = new double[4];

		//	Initialize temperature array for error checking later
		for (int i = 0; i < temps.length; i++) {
			temps[i] = -666;
		}
		
		//	Get tank temperatures from the LongTerm database
		ArrayList<SensorResponse> ltl = ltdb.getHotWaterTemperatures();

		for (SensorResponse response : ltl) {
			if(response.getName().equals("DHW"))
				temps[0] = Double.parseDouble(response.getValueString());
			else if(response.getName().equals("DHW IN"))
				temps[1] = Double.parseDouble(response.getValueString());
			else if(response.getName().equals("DHW OUT"))
				temps[2] = Double.parseDouble(response.getValueString());
		}

		if(temps[0] == -666) {
			log.error("Current State unable to find current Domestic Hot Water Temperature.");
			temps[0] = 0.0;
			ErrorDatabaseResult.activateError(ErrorDatabaseResult.LONG_TERM_FAIL);
		}
		if(temps[1] == -666) {
			log.error("Current State unable to find current Heat Pump Domestic Hot Input Temperature.");
			temps[1] = 0.0;
			ErrorDatabaseResult.activateError(ErrorDatabaseResult.LONG_TERM_FAIL);
		}
		if(temps[2] == -666) {
			log.error("Current State unable to find current Heat Pump Domestic Hot Output Temperature.");
			temps[2] = 0.0;
			ErrorDatabaseResult.activateError(ErrorDatabaseResult.LONG_TERM_FAIL);
		}
		
		return temps;
	}
}
